package config

import (
	"fmt"
	"log"
	"time"
	"os"
	"github.com/go-ini/ini"
)
// Logs 的基本信息
type Logs struct {
	LogSavePath     string
	LogSaveName     string
	LogFileExt      string
	TimeFormat      string
	RuntimeRootPath string
}
// LogsSetting 初始化
var LogsSetting = &Logs{}

// Database 数据库 的基本信息
type Database struct {
	Type     string
	User     string
	Password string
	Host     string
	Name     string
}

// DatabaseSetting 初始化
var DatabaseSetting = &Database{}

// Redis 的基本信息
type Redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

// RedisSetting 初始化
var RedisSetting = &Redis{}

// Email 的基本信息
type Email struct {
	Username string
	Password string
	Server   string
	Port     int
	Admins   string
}

// EmailSetting 初始化
var EmailSetting = &Email{}

var cfg *ini.File

// Setup setting init
func Setup() {
	var err error
	gopath := os.Getenv("GOPATH")

	fmt.Println("gopath + /src/bbtradeByGo/ + conf/app.ini", gopath + "/src/bbtradeByGo/" + "conf/app.ini")
	cfg, err = ini.Load(gopath + "/src/bbtradeByGo/" + "conf/app.ini")

	if err != nil {
		fmt.Printf("config.Setup, fail to parse 'conf/app.ini': %v", err)
	}

	mapTo("logs", LogsSetting)
	mapTo("database", DatabaseSetting)
	mapTo("redis", RedisSetting)
	mapTo("email", EmailSetting)
	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second
}

// mapTo map section
func mapTo(section string, v interface{}) {
	err := cfg.Section(section).MapTo(v)
	if err != nil {
		log.Fatalf("Cfg.MapTo RedisSetting err: %v", err)
	}
}
